#include "RawImageDataHelp.h"

void OCTViewr2::FreeRawImageData(OCTViewr2::RAW_IMAGE_DATA &data)
{
    if(data.ptr){
        delete [] data.ptr;
        data.ptr=nullptr;
    }
    data.cols=0;
    data.rows=0;
    data.depth=0;
    data.totalByte=0;
    data.type=BUF_DATA_TYPE_U8C1;
}

void OCTViewr2::CalcRawImageDataToatalbyte(OCTViewr2::RAW_IMAGE_DATA &data)
{
    if(data.ptr){
        size_t bytelen=1;
        switch (data.type) {
        case BUF_DATA_TYPE_U16C1:
            bytelen=2;
            break;
        case BUF_DATA_TYPE_U8RGB:
        case BUF_DATA_TYPE_U8BGR:
        case BUF_DATA_TYPE_U8C3:
            bytelen=3;
            break;
        case BUF_DATA_TYPE_U8RGBA:
        case BUF_DATA_TYPE_U8BGRA:
        case BUF_DATA_TYPE_U8C4:
            bytelen=4;
            break;
        case BUF_DATA_TYPE_U8C1:
        default:
            bytelen=1;
            break;
        }
        if(data.rows>0) bytelen*=static_cast<size_t>(data.cols);
        if(data.rows>0) bytelen*=static_cast<size_t>(data.rows);
        if(data.depth>0) bytelen*=static_cast<size_t>(data.depth);
        data.totalByte=bytelen;
    }else{
        data.totalByte=0;
        data.cols=0;
        data.rows=0;
        data.depth=0;
        data.type=BUF_DATA_TYPE_U8C1;
    }
}

void OCTViewr2::AllocateRawImageDataMem(OCTViewr2::RAW_IMAGE_DATA &data, int type, int cols, int rows, int depth)
{
    FreeRawImageData(data);
    data.type=type;
    data.cols=cols;
    data.rows=rows;
    data.depth=depth;
    size_t bytelen=1;

    switch (data.type) {
    case BUF_DATA_TYPE_U16C1:
        bytelen=2;
        break;
    case BUF_DATA_TYPE_U8RGB:
    case BUF_DATA_TYPE_U8BGR:
    case BUF_DATA_TYPE_U8C3:
        bytelen=3;
        break;
    case BUF_DATA_TYPE_U8RGBA:
    case BUF_DATA_TYPE_U8BGRA:
    case BUF_DATA_TYPE_U8C4:
        bytelen=4;
        break;
    case BUF_DATA_TYPE_U8C1:
    default:
        bytelen=1;
        break;
    }
    if(data.cols>0) bytelen*=static_cast<size_t>(data.cols);
    if(data.rows>0) bytelen*=static_cast<size_t>(data.rows);
    if(data.depth>0) bytelen*=static_cast<size_t>(data.depth);
    data.totalByte=bytelen;

    if(data.totalByte){
        data.ptr=new char[data.totalByte];
    }

    CalcRawImageDataToatalbyte(data);
}
